package com.tools.config;

import cn.hutool.extra.servlet.ServletUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.tools.security.base.RequestMethodEnum;
import com.tools.commons.annotation.AnonymousAccess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.lang.NonNull;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

@Slf4j
public class AuthFilterWitheURLConfigureImpl implements AuthFilterWitheURLConfigure {
    private final PathMatcher pathMatcher = new AntPathMatcher();
    private final UrlPathHelper urlPathHelper = new UrlPathHelper();
    private final Map<String, Set<String>> anonymousUrls = Maps.newHashMap();
    private final ApplicationContext applicationContext;
    @Override
    public boolean shouldNotFilter(@NonNull HttpServletRequest request) {
        if (log.isDebugEnabled()) {
            log.debug("Request URL: [{}], URI: [{}], Request Method: [{}], IP: [{}]",
                    request.getRequestURL(),
                    request.getRequestURI(),
                    request.getMethod(),
                    ServletUtil.getClientIP(request));
        }
        String requestMethod = request.getMethod();
        String reqUrl = urlPathHelper.getRequestUri(request);

        RequestMethodEnum method = RequestMethodEnum.valueOf(requestMethod);
        boolean result = anonymousUrls.get(RequestMethodEnum.ALL.getType()).stream().anyMatch(url -> pathMatcher.match(url, reqUrl));
        return result || anonymousUrls.get(method.getType()).stream().anyMatch(url -> pathMatcher.match(url, reqUrl));
    }

    public AuthFilterWitheURLConfigureImpl(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        defaultConfig();
    }

    private void defaultConfig() {
        // 搜寻匿名标记 url： @AnonymousAccess
        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
        // 获取匿名标记
        Map<String, Set<String>> anonymousUrls = getAnonymousUrl(handlerMethodMap);

        this.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType())).permitAll()
                // POST
                .antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType())).permitAll()
                // PUT
                .antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType())).permitAll()
                // PATCH
                .antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType())).permitAll()
                // DELETE
                .antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType())).permitAll()
                // 所有类型的接口都放行
                .antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType())).permitAll();

    }

    private static Map<String, Set<String>> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
        Map<String, Set<String>> anonymousUrls = new HashMap<>(6);
        Set<String> get = new HashSet<>();
        Set<String> post = new HashSet<>();
        Set<String> put = new HashSet<>();
        Set<String> patch = new HashSet<>();
        Set<String> delete = new HashSet<>();
        Set<String> all = new HashSet<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
            HandlerMethod handlerMethod = infoEntry.getValue();
            AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
            if (null != anonymousAccess) {
                List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods());
                RequestMethodEnum request = RequestMethodEnum.find(requestMethods.size() == 0 ? RequestMethodEnum.ALL.getType() : requestMethods.get(0).name());
                switch (Objects.requireNonNull(request)) {
                    case GET:
                        get.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                        break;
                    case POST:
                        post.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                        break;
                    case PUT:
                        put.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                        break;
                    case PATCH:
                        patch.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                        break;
                    case DELETE:
                        delete.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                        break;
                    default:
                        all.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
                        break;
                }

            }
        }
        anonymousUrls.put(RequestMethodEnum.GET.getType(), get);
        anonymousUrls.put(RequestMethodEnum.POST.getType(), post);
        anonymousUrls.put(RequestMethodEnum.PUT.getType(), put);
        anonymousUrls.put(RequestMethodEnum.PATCH.getType(), patch);
        anonymousUrls.put(RequestMethodEnum.DELETE.getType(), delete);
        anonymousUrls.put(RequestMethodEnum.ALL.getType(), all);
        return anonymousUrls;
    }

    public Configure antMatchers(HttpMethod method, String... antPatterns) {
        return new Configure(this, method, antPatterns);
    }

    public Configure antMatchers(HttpMethod method, Set<String> antPatterns) {
        return new Configure(this, method, antPatterns);
    }

    public Configure antMatchers(String... antPatterns) {
        return new Configure(this, null, antPatterns);
    }

    public Configure antMatchers(Set<String> antPatterns) {
        return new Configure(this, null, antPatterns);
    }

    public static class Configure {
        private final AuthFilterWitheURLConfigureImpl baseInterceptor;
        private final Set<String> antPatterns;
        private final RequestMethodEnum method;

        public Configure(AuthFilterWitheURLConfigureImpl baseInterceptor, HttpMethod method, String... antPatterns) {
            this(baseInterceptor, method, Sets.newHashSet(antPatterns));
        }

        public Configure(AuthFilterWitheURLConfigureImpl baseInterceptor, HttpMethod method, Set<String> antPatterns) {
            this.baseInterceptor = baseInterceptor;
            this.method = RequestMethodEnum.find(method);
            this.antPatterns = antPatterns;
        }

        public AuthFilterWitheURLConfigureImpl permitAll() {
            Set<String> urls = baseInterceptor.anonymousUrls.getOrDefault(method.getType(), Sets.newHashSet());
            urls.addAll(this.antPatterns != null ? this.antPatterns : Sets.newHashSet());
            baseInterceptor.anonymousUrls.put(method.getType(), urls);
            return baseInterceptor;
        }
    }
}
